﻿using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Read.Api.Application.Commands.Traceability;
using B.S.Database.Read.Api.Dtos.RequsetDtos;
using MediatR;

namespace B.S.Database.Read.Api.Application.CommandHandler.Traceability
{
    public class TraceabilityShowCommandHandler : IRequestHandler<TraceabilityShowCommands, Apiresult<ApiPaging<TraceabilityDtos>>>
    {
        private readonly IBaseResotity<Basic_Traceability> traceabilityResotity;
        private readonly IBaseResotity<Goods_Infomation> goodsResotity;

        public TraceabilityShowCommandHandler(IBaseResotity<Basic_Traceability> TraceabilityResotity,IBaseResotity<Goods_Infomation> GoodsResotity)
        {
            traceabilityResotity = TraceabilityResotity;
            goodsResotity = GoodsResotity;
        }
        public Task<Apiresult<ApiPaging<TraceabilityDtos>>> Handle(TraceabilityShowCommands request, CancellationToken cancellationToken)
        {
            Apiresult<ApiPaging<TraceabilityDtos>> res = new Apiresult<ApiPaging<TraceabilityDtos>>();
            res.Code = ApiEnums.成功;
            res.Message = ApiEnums.成功.ToString();
            var list = from a in traceabilityResotity.GetAll()
                       join b in goodsResotity.GetAll() on a.GoodsId equals b.GoodsId
                       where a.IsDelete==false
                       select new TraceabilityDtos
                       {
                           TraceabilityId = a.TraceabilityId,
                           GoodsId = a.GoodsId,
                           GoodsName = b.GoodsName,
                           Production_Batch = a.Production_Batch,
                           Quality_Guarantee = a.Quality_Guarantee,
                           Production_License = a.Production_License,
                           Manufacturing_Enterprise = a.Manufacturing_Enterprise,
                           Information_Completeness = a.Information_Completeness,
                           NumberOfExports = a.NumberOfExports,
                           Cover_Image = a.Cover_Image,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                       };
            int count = list.Count();
            int pagecount = (int)(count * 1.0 / request.Size);
            list = list.Skip((request.Index - 1) * request.Size).Take(request.Size);
            ApiPaging<TraceabilityDtos> paging = new ApiPaging<TraceabilityDtos>();
            paging.Count = count;
            paging.Pagecount = pagecount;
            paging.Items = list.ToList();
            res.Data = paging;
            return Task.FromResult(res);
        }
    }
}
